package sk.demo.boot;

import cn.org.atool.fluent.mybatis.spring.MapperFactory;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.logging.stdout.StdOutImpl;
import org.apache.ibatis.session.ExecutorType;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.Collections;

/**
 * @author sk.z
 */
@ComponentScan(basePackages = "sk.demo.dao")
@MapperScan(basePackages="sk.demo.mapper")
@Configuration
public class Config {

    @Bean
    public DataSource dataSource(){
        BasicDataSource dataSource= new BasicDataSource();
        dataSource.setUrl("jdbc:mysql://localhost:3306/hh");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        dataSource.setDefaultCatalog("hh");
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setInitialSize(5);
        dataSource.setConnectionInitSqls(Collections.singleton("set names utf8mb4;"));
        dataSource.setLogAbandoned(true);
        dataSource.setMaxConnLifetimeMillis(100);
        dataSource.setMaxIdle(100);
        dataSource.setMaxWaitMillis(30000);
        dataSource.setMinEvictableIdleTimeMillis(300000);
        dataSource.setMinIdle(10);
        dataSource.setRemoveAbandonedOnBorrow(true);
        dataSource.setRemoveAbandonedTimeout(600);
        dataSource.setTestOnBorrow(true);
        dataSource.setTestOnCreate(false);
        dataSource.setTestOnReturn(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setValidationQuery("select 1;");
        dataSource.setValidationQueryTimeout(500);
        dataSource.setDefaultAutoCommit(true);
        dataSource.setDefaultTransactionIsolation(2);
        dataSource.setConnectionProperties("autoReconnectForPools=true;useUnicode=true;characterEncoding=UTF-8;autoReconnect=true");
        return dataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCacheEnabled(true);
        configuration.setUseGeneratedKeys(true);
        configuration.setDefaultExecutorType(ExecutorType.REUSE);
        configuration.setLogImpl(StdOutImpl.class);
        bean.setConfiguration(configuration);
        return bean;
    }

    @Bean
    public MapperFactory mapperFactory(){
        return new MapperFactory();
    }
}
